<?php

namespace app\admin\controller;


use app\common\model\AdminModel;
use app\common\model\AgentLavel;
use app\common\model\UserModel as models;
use app\common\model\UserSet;
use app\common\traites\PublicCrudTrait;
use app\validate\User as validates;
use think\exception\ValidateException;
use think\facade\Db;

class User extends Base
{
    protected $model;
    use PublicCrudTrait;

    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //获取列表信息
    public function index()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post = array_filter($this->request->post());
        $map = $date = [];
        isset($post['user_name']) && $map [] = ['a.user_name', 'like', '%' . $post['user_name'] . '%'];
        isset($post['phone']) && $map[] = ['a.phone', '=', $post['phone']];
        isset($post['market_uid']) && $map [] = ['b.user_name', 'like', '%' . $post['market_uid'] . '%'];
        isset($post['type']) && $map [] = ['a.type', '=', $post['type']];

        //代理查询存在是，清除其他查询只保留代理查询
        isset($post['agent_name']) && $map ['agent_name'] = $post['agent_name'];
        isset($post['start']) && $date['start'] = $post['start'];
        isset($post['end']) && $date['end'] = $post['end'];

        $list = $this->model->page_list($map, $limit, $page, $date);
        return $this->success($list);
    }

    //代理商个人信息
    public function agent()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        $list = $this->model->page_one($limit, $page);
        return $this->success($list);
    }

    public function add()
    {
        //过滤数据
        $postField = 'xima_lv,phone,market_uid,user_name,money_balance,money_freeze,agent_rate,pwd,withdraw_pwd,nickname,type,status,is_real_name,is_fictitious,id_code';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        try {
            validate(validates::class)->scene('add')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //$post = array_filter($post);

        //查询是否重复的用户名
        $find = $this->model->where('user_name', $post['user_name'])->find();
        if ($find) return $this->failed('用户已存在');

        //洗码率存入另外的表
        $xima = 0;
        if (isset($post['xima_lv']) && $post['xima_lv'] > 0) {
            if ($post['xima_lv'] > 100) admin_show([], 0, '洗码率不能高于100%');
            $xima = $post['xima_lv'];
            unset($post['xima_lv']);
        }

        //加密密码
        $post['pwd'] = !empty($post['pwd']) && isset($post['pwd']) ? pwdEncryption($post['pwd']) : home_Initial_pwd();
        //分销比例

        if (!isset($post['agent_rate']) || empty($post['agent_rate'])) $post['agent_rate'] = 0;
        if ($post['type'] != 1) $post['agent_rate'] = 0;//用户没有代理分销金额
        //生成用户邀请码
        $post['invitation_code'] = generateCode();

        if (session('admin_user.agent')) {
            //代理添加代理

            return $this->agent_add($post, $xima);
        } else {
            return $this->user_add($post, $xima);
        }
    }

    /**
     * 修改方法
     * @return mixed
     */
    public function edit()
    {
        //过滤数据
        $postField = 'xima_lv,phone,market_uid,user_name,money_balance,money_freeze,agent_rate,pwd,withdraw_pwd,nickname,type,status,is_real_name,is_fictitious,id';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //验证数据
        try {
            validate(validates::class)->scene('edit')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //$post = array_filter($post);
        //查询是否重复的用户名
        $find = $this->model->where('user_name', $post['user_name'])->where('id', '<>', $post['id'])->find();
        if ($find) return $this->failed('用户已存在');
        //加密密码
        !empty($post['pwd']) && $post['pwd'] = pwdEncryption($post['pwd']);

        //洗码率存入另外的表
        $xima = 0;
        if (isset($post['xima_lv']) && $post['xima_lv'] > 0) {
            $xima = $post['xima_lv'];
        }
        unset($post['xima_lv']);

        return $this->user_edit($post, $xima);
    }


    //判断业务员存不存在
    public function is_admin($post)
    {
        if (!isset($post['market_uid']) || empty($post['market_uid'])) return false;
        $admin = (new AdminModel())->find($post['market_uid']);
        if (!$admin) return false;
        return $post;
    }

    //修改虚拟账号
    public function is_status()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->is_fictitious = $find->is_fictitious == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }

    /**
     * money_change_type: 1 1增加
     *uid: 20  用户id
     *change_money:  变化金额
     *money_ststus: 90 90余额修改
     *用户余额修改
     */
    public function money_edit()
    {
        $postField = 'money_change_type,change_money,uid,money_ststus';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        $post = array_filter($post);
        //验证数据
        try {
            validate(validates::class)->scene('money')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //查询当前用户的余额
        $find = $this->model->find($post['uid']);
        if (!$find) return $this->failed('用户不存在');

        // '编辑可用余额'; 90
        if ($post['money_ststus'] == 90) {
            return $this->balance_edit($post, $find);
        }

        if ($post['money_ststus'] == 91) {
            return $this->frozen_edit($post, $find);
        }

        if ($post['money_ststus'] == 92) {
            return $this->points_edit($post, $find);
        }

        return $this->failed('请求错误');
    }
    /**
     * 用户余额修改
     * @param $post /数据
     * @param $find /模型查询数据
     * @return mixed
     */
    protected function balance_edit($post, $find)
    {

        $balance = $find->money_balance;
        //查询用户钱是否够扣
        if ($find->money_balance < $post['change_money'] && $post['money_change_type'] != 1) return $this->failed('用户钱包不够');

        //state是 1时是增加
        $find->money_balance = $post['money_change_type'] == 1 ? $find->money_balance + $post['change_money'] : $find->money_balance - $post['change_money'];
        //执行修改数据
        $save = false;
        Db::startTrans();
        try {
            $find->save();
            //写操作日志
            (new \app\common\model\MoneyLog())->insert([
                'create_time' => date('Y-m-d H:i:s'),
                'type' => 3,
                'status' => 101,
                'money_before' => $balance,
                'money_end' => $find->money_balance,
                'money' => $post['change_money'],
                'uid' => $find->id,
                'market_uid' => session('admin_user.id'),
            ]);
            $save = true;
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    /**
     * @param $post /数据
     * @param $find /模型查询数据
     * @return mixed
     * 用户冻结余额修改
     */
    protected function frozen_edit($post, $find)
    {

        $balance = $find->money_freeze;
        //查询用户冻结金额是否够扣
        if ($find->money_freeze < $post['change_money'] && $post['money_change_type'] != 1) return $this->failed('用户钱包不够');

        //state是 1时是增加
        $find->money_freeze = $post['money_change_type'] == 1 ? $find->money_freeze + $post['change_money'] : $find->money_freeze - $post['change_money'];
        //执行修改数据
        $save = false;
        Db::startTrans();
        try {
            $find->save();
            //写操作日志
            (new \app\common\model\MoneyLog())->insert([
                'create_time' => date('Y-m-d H:i:s'),
                'type' => 3,
                'status' => 101,
                'money_before' => $balance,
                'money_end' => $find->money_freeze,
                'money' => $post['change_money'],
                'uid' => $find->id,
                'market_uid' => session('admin_user.id'),
            ]);
            $save = true;
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    /**
     ** @param $post /数据
     * @param $find /模型查询数据
     * 用户积分修改
     */
    public function points_edit($post, $find)
    {
        $balance = $find->points;
        //查询用户冻结金额是否够扣
        if ($find->money_freeze < $post['change_money'] && $post['money_change_type'] != 1) return $this->failed('用户钱包不够');

        //state是 1时是增加
        $find->points = $post['money_change_type'] == 1 ? $find->money_freeze + $post['change_money'] : $find->money_freeze - $post['change_money'];
        //执行修改数据
        $save = false;
        Db::startTrans();
        try {
            $find->save();
            //写操作日志
            (new \app\common\model\MoneyLog())->insert([
                'create_time' => date('Y-m-d H:i:s'),
                'type' => 3,
                'status' => 301,
                'money_before' => $balance,
                'money_end' => $find->points,
                'money' => $post['change_money'],
                'uid' => $find->id,
                'market_uid' => session('admin_user.id'),
            ]);
            $save = true;
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }

    public function agent_add($post, $xima)
    {
        $post['agent_id'] = session('admin_user.id');
        if ($post['type'] != 1) {

        } else {
            //给自己增加下级代理
            // 1查询自己所有下级，并获取所有下级的 分销奖励加上自己的 不能超过 固定值
            session('admin_user.agent_rate');
            $total_agent_sale = get_config('app_agent_sale')->value;
            if ($post['agent_rate'] > $total_agent_sale) return admin_show([], 0, '分销比例不能大于' . $total_agent_sale);

            $agent_rate = AgentLavel::agent_down_all(session('admin_user.id'));//该用户所有分销金额 包括自己
            if (($agent_rate + $post['agent_rate']) > $total_agent_sale) {
                return admin_show([], 0, '分销链分销比例为:' . ($agent_rate + $post['agent_rate']) . '不合法');
            }
        }
        //添加的时候，写入 洗码率，写入代理的所有上级代理
        $save = false;
        Db::startTrans();
        try {
            $this->model->save($post);
            Db::name('dianji_user_set')->insert(['u_id' => $this->model->id, 'xima_lv' => $xima]);

            if ($post['type'] == 1) {
                //组装插入代理表数据
                //查询用户上级
                $user_all = AgentLavel::agent_pid($post['agent_id']);
                if ($user_all) {
                    sort($user_all);
                    $num = 0;
                    foreach ($user_all as $key => $value) {
                        if ($value == 0) continue;
                        $data[$num]['agent_id'] = $this->model->id;
                        $data[$num]['agent_pid'] = $value;
                        $data[$num]['agent_pid_level'] = $num;
                        $data[$num]['rate'] = $post['agent_rate'];
                        $num++;
                    }
                    AgentLavel::insertAll($data);
                } else {
                    AgentLavel::insert(['agent_id' => $this->model->id, 'agent_pid' => $post['agent_id'], 'agent_pid_level' => 1, 'rate' => $post['agent_rate']]);
                }
            }
            $save = true;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if ($save) return admin_show();
        return admin_show([], 0);
    }

    //用户添加
    public function user_add($post, $xima)
    {
        //添加常规会员开始
        if ($post['type'] != 1) {
            unset($post['id_code']);
        } else {
            //添加常规会员结束
            //添加代理开始

            $total_agent_sale = get_config('app_agent_sale')->value;

            if ($post['agent_rate'] > $total_agent_sale) return admin_show([], 0, '分销比例不能大于' . $total_agent_sale);
            //后台管理员添加代理的时候。需要填写上级ID
            $post['agent_id'] = 0;
            if (isset($post['id_code']) && $post['id_code'] > 0) {
                // 上级ID存在的时候，
                // 1 需要查询该代理链 的分销比例是否大鱼 配置的 分销比例
                // 2 并统计该分销链的分销比例是否大鱼配置的分销比例
                $agent_rate = AgentLavel::agent_down_all($post['id_code']);//该用户所有分销金额 包括自己
                if (($agent_rate + $post['agent_rate']) > $total_agent_sale) {
                    return admin_show([], 0, '分销链分销比例为:' . ($agent_rate + $post['agent_rate']) . '不合法');
                }
                $post['agent_id'] = $post['id_code'];
                unset($post['id_code']);
            }
        }

        //添加的时候，写入 洗码率，写入代理的所有上级代理
        $save = false;
        Db::startTrans();
        try {
            $this->model->save($post);
            Db::name('dianji_user_set')->insert(['u_id' => $this->model->id, 'xima_lv' => $xima]);

            if ($post['type'] == 1) {
                //组装插入代理表数据
                //查询用户上级
                $user_all = AgentLavel::agent_pid($post['agent_id']);
                if ($user_all) {
                    sort($user_all);
                    $num = 0;
                    foreach ($user_all as $key => $value) {
                        if ($value == 0) continue;
                        $data[$num]['agent_id'] = $this->model->id;
                        $data[$num]['agent_pid'] = $value;
                        $data[$num]['agent_pid_level'] = $num;
                        $data[$num]['rate'] = $post['agent_rate'];
                        $num++;
                    }
                    (new AgentLavel())->saveAll($data);
                } else {
                    AgentLavel::insert(['agent_id' => $this->model->id, 'agent_pid' => 0, 'agent_pid_level' => 0, 'rate' => $post['agent_rate']]);
                }
            }
            $save = true;
            Db::commit();
        } catch (\Exception $e) {
            return admin_show([], 0, $e->getMessage());
            Db::rollback();
        }

        if ($save) return admin_show();
        return admin_show([], 0, '新增失败');
    }

    public function user_edit($post, $xima)
    {
        if ($post['type'] != 1 || !isset($post['agent_rate']) || $post['agent_rate'] <= 0) {
            unset($post['id_code']);
            $post['agent_rate'] = 0;
        } else {
            $total_agent_sale = get_config('app_agent_sale')->value;
            if ($post['agent_rate'] > $total_agent_sale) return admin_show([], 0, '分销比例不能大于' . $total_agent_sale);
            //后台管理员添加代理的时候。需要填写上级ID
            //修改 不能修改 上级ID
            //修改分销比例
            $agent_rate = AgentLavel::agent_down_all($post['id'], true);//该用户所有分销金额 包括自己

            if (($agent_rate + $post['agent_rate']) > $total_agent_sale) {
                return admin_show([], 0, '分销链分销比例为:' . ($agent_rate + $post['agent_rate']) . '不合法');
            }
        }

        $save = false;
        Db::startTrans();
        try {
            $this->model->update($post);
            //写入洗马数据
            if ($xima >= 0) {
                $db = Db::name('dianji_user_set');
                if ($db->where('u_id', $post['id'])->find()) {
                    $db->where('u_id', $post['id'])->update(['xima_lv' => $xima]);
                } else {
                    Db::name('dianji_user_set')->insert(['u_id' => $post['id'], 'xima_lv' => $xima]);
                }
            }
            //更改 代理商信息
            if ($post['type'] == 1) {
                AgentLavel::where('agent_id', $post['id'])->update(['rate' => $post['agent_rate']]);
            }
            Db::commit();
            $save = true;
        } catch (\Exception $e) {
            Db::rollback();
        }

        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }

    public function xian_hong()
    {

        $postField = 'id,bjl_xian_hong_xian_max,bjl_xian_hong_zhuang_max,bjl_xian_hong_he_max,is_xian_hong,bjl_xian_hong_zhuang_dui_max,bjl_xian_hong_xian_dui_max,bjl_xian_hong_lucky6_max,lh_xian_hong_long_max,lh_xian_hong_hu_max,lh_xian_hong_he_max,bjl_xian_hong_xian_min,bjl_xian_hong_zhuang_min,bjl_xian_hong_he_min,bjl_xian_hong_zhuang_dui_min,lh_xian_hong_he_min,bjl_xian_hong_xian_dui_minbjl_xian_hong_lucky6_min,lh_xian_hong_long_min,lh_xian_hong_hu_min';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        $user_set = UserSet::where('u_id',$post['id'])->find();
        $post['u_id'] = $post['id'];
        unset($post['id']);
        if (empty($user_set)){
            UserSet::user_insert(0,0,0,$post);
        }
        $user_set->save($post);
        return $this->success([]);
    }
}